package com.health.viewscontrols.medical.device.bo;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleIndicateCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.clj.fastble.utils.HexUtil;
import com.health.httpbean.model.BpModel;
import com.health.httpbean.model.PoModel;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;

import java.util.List;
import java.util.UUID;

public class BOYuyueActivity extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_NOTIFY = UUID.fromString("0000ffe4-0000-1000-8000-00805f9b34fb");

    private String mBloodOxygen;//血氧值
    private String mHeartRate;//心率值
    private BleDevice fastBleDevice;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bo_pc_YUYUE);
        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 15000)
                .setConnectOverTime(20000)
                .setOperateTimeout(15000);

//        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setDeviceMac(deviceEnum.getMac())                  // 只扫描指定mac的设备，可选
//                .setAutoConnect(true)      // 连接时的autoConnect参数，可选，默认false
//                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒
//                .build();
//        BleManager.getInstance().initScanRule(scanRuleConfig);

        startDevice();
    }

    @Override
    public void startDevice() {
        if (fastBleDevice == null) {
            showProgressDialog("正在连接" + deviceEnum.getTitle());
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    Log.e(TAG, "onScanning: " + bleDevice.getName() + "  " + bleDevice.getMac() );
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connectionPwBle();
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
            showProgressDialog("等待接收血氧数据");
        }
    }

    private void connectionPwBle() {
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");
                showProgressDialog("正在连接血氧设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " +  exception.toString());
                blueToothState.setText("蓝牙连接失败");
                connectionPwBle();
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                blueToothState.setText("蓝牙已连接");
                fastBleDevice = bleDevice;
                showProgressDialog("等待接收血氧数据");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPwNotify(bleDevice);
                    }
                },1000);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showResultState("");
                        release();
                    }
                }, 30 * 1000);

                showProgressDialog("蓝牙连接成功，请测量30秒出结果");
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
                disconnectDevice();
                cancelProgressDialog();
            }
        });
    }

    private void getPwNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                UUID_SERVICE.toString(),
                UUID_NOTIFY.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "onCharacteristicChanged: "+ hexString );
                        if (!TextUtils.isEmpty(hexString) && hexString.length() > 18) {
                            mHeartRate = Integer.parseInt(hexString.substring(6,10), 16) + "";
                            mBloodOxygen = Integer.parseInt(hexString.substring(10, 12), 16) + "";
                            tv_state.setText("实时测量数据：");
                            tv_result.setText("脉率:" + mHeartRate + "bpm\t\t" + "血氧:" + mBloodOxygen + "%");
                        }
                    }
                });
    }

    private void showResultState(String resultStringCH) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cancelProgressDialog();
                tv_state.setText("测试结果:" + resultStringCH);
                tv_result.setText("脉率:" + mHeartRate + "bpm\t\t" + "血氧:" + mBloodOxygen + "%");
                Log.e(TAG, "setStatusPre: " + mBloodOxygen + "/" + mHeartRate);
                if (!TextUtils.isEmpty(mBloodOxygen)) {
                    DeviceShowSaveData.getDataShow(mBloodOxygen + "/" + mHeartRate, BluetoothConstant.XUEYANG_LIKANG_KRK);
                    PoModel poModel = new PoModel();
                    poModel.setBloodOxygenSaturation(mBloodOxygen + "");
                    poModel.setHeartRate(mHeartRate + "");
                    DeviceShowSaveData.saveXueyangyuyue(GsonUtils.toJson(poModel));
                }
            }
        });
    }

    @Override
    public void update(String hexString) {

    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
            release();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void release() {
        if (fastBleDevice != null) {
            BleManager.getInstance().stopNotify(fastBleDevice, UUID_SERVICE.toString(), UUID_NOTIFY.toString());
            //断开设备
            BleManager.getInstance().disconnectAllDevice();
            BleManager.getInstance().destroy();
            fastBleDevice = null;
        }
        try {
            BleManager.getInstance().cancelScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
